package pl.rgolcz.antnet;

import java.io.BufferedReader;
import java.io.IOException;

import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;

/**
 * Read graph from provided reader (file, stdin or whatever).
 * The format is:
 * <pre>
 * n            - number of vertices (each vertex is of Integer type with the numbers (0... n-1)
 * v1 v2 weight - list of edges
 * v1 v2 weight
 * </pre>
 * @author ragg
 *
 */
public class GraphReader
{
    private BufferedReader reader;

    public GraphReader(BufferedReader reader)
    {
        this.reader = reader;
    }
    
    public Graph<Integer, IWeightedEdge> read() throws IOException
    {
        Graph<Integer, IWeightedEdge> graph = new UndirectedSparseGraph<>();
        
        String line;
        line = reader.readLine();
        int size = Integer.parseInt(line.trim());
        for(int i = 0; i < size; i++)
        {
            graph.addVertex(i);
        }
        
        while((line = reader.readLine()) != null)
        {
            String[] tokens = line.trim().split("\\s");
            if(tokens.length >= 3)
            {
                int from = Integer.parseInt(tokens[0]);
                int to = Integer.parseInt(tokens[1]);
                double weight = Double.parseDouble(tokens[2]);
                graph.addEdge(new WeightedEdge(weight), from, to);
            }
        }
        
        reader.close();
        
        return graph;
    }
}
